package com.tender.enums;

import lombok.Getter;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

@Getter
public enum ErrorTypeEnum {

    DATA_NOT_EMPTY(100000000, "data not empty", "%s数据不能为空"),
    RECORD_HAS_EXISTS(100000001, "record has exists", "%s数据已经存在"),
    ENCRYPT_DATA_2_RETURN_FRONT(100000010, "", "返回给前端的数据加密失败"),
    REQUEST_PARAM_TIME_NOT_EXISTS(100000020, "", "请求参数time必填"),
    REQUEST_PARAM_EXPIRED(100000030, "", "请求参数已过期"),
    KEY_AES_128_NOT_EXISTS(100000040, "", "AES密钥不能为空"),
    AES_IV_NOT_EXISTS(100000050, "", "AES偏移量不能为空"),
    KEY_AES_128_DECRYPT_ERROR(100000060, "", "AES解密失败"),
    KEY_AES_128_ENCRYPT_ERROR(100000070, "", "AES加密失败"),
    DEVICE_TYPE_INVALID(100000080, "", "设备类型无效"),
    SYSTEM_INVOKE_TIME_OUT_ERROR(100000090, "", "系统调用超时"),
    SYSTEM_INVOKE_WITH_ERROR(100000100, "", "系统调用异常"),
    SYSTEM_INVOKE_RATE_LIMITER_ERROR(100000110, "", "系统访问过频，请稍后再试"),

    /* --------------------------- web socket start --------------------------------- */
    WEB_SOCKET_CLOSE_EXP(200000000, "", "web socket关闭异常"),
    WEB_SOCKET_PARSE_HOST_INFO_EXP(200000010, "", "web socket解析host info异常"),
    WEB_SOCKET_MSG_SAVE_INFO_EXP(200000020, "", "web socket消息入db失败"),
    /* --------------------------- web socket end --------------------__------------- */

    ;
    private final Integer code;

    // 异常描述英文
    private final String errorMsgEn;

    // 异常描述中文
    private final String errorMsgCn;

    ErrorTypeEnum(Integer code, String errorMsgEn, String errorMsgCn) {
        this.code = code;
        this.errorMsgEn = errorMsgEn;
        this.errorMsgCn = errorMsgCn;
    }

    // 初始化 code2MsgMap 和 code2ErrorMap，用来加速查询
    private static Map<Integer, String> code2MsgMap = null;
    private static Map<Integer, ErrorTypeEnum> code2ErrorMap = null;

    static {
        ErrorTypeEnum[] values = ErrorTypeEnum.values();
        code2MsgMap = Arrays.stream(values).collect(Collectors.toMap(ErrorTypeEnum::getCode, ErrorTypeEnum::getErrorMsgCn));
        code2ErrorMap = Arrays.stream(values).collect(Collectors.toMap(ErrorTypeEnum::getCode, v -> v));
    }

    public static String getMessage(Integer code) {
        // return Arrays.stream(ErrorCodeEnum.values()).filter(item -> item.getCode().intValue() == code)
        //         .findFirst().map(ErrorCodeEnum::getMessage)
        //         .orElse(null);
        if (null != code) {
            return code2MsgMap.get(code);
        }
        return null;
    }

    public static ErrorTypeEnum getEnum(Integer code) {
        // return Arrays.stream(ErrorCodeEnum.values()).filter(item -> item.getCode().intValue() == code)
        //         .findFirst()
        //         .orElse(null);
        if (null != code) {
            return code2ErrorMap.get(code);
        }
        return null;
    }

}
